package com.acme.team02.chat.server.connection;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;

import com.acme.team02.chat.server.ChatServer;
import com.acme.team02.chat.server.MessageManager;
import com.acme.team02.chat.server.UserManager;
import com.acme.team02.chat.server.connection.Connect.OnMessageReceivedListener;
import com.acme.team02.chat.server.domain.User;

public class ConnectionManager implements OnMessageReceivedListener {
	int port;
	UserManager userManager;
	MessageManager msgManager;

	public ConnectionManager(int port, UserManager userManager, MessageManager msgManager) {
		this.port = port;
		this.userManager = userManager;
		this.msgManager = msgManager;
	}

	/**
	 * Start listening for new connections
	 */
	public void startServer() {
		try (ServerSocket listener = new ServerSocket(port)) {
			
			System.out.println("Server started...");

			while (true) {
				Connect connection;
				Socket client;

				client = listener.accept();
				
				System.out.println("Client connected" + client.getRemoteSocketAddress().toString());				
				
				connection = new Connect(client, this);
				userManager.addUser(connection);
				Thread t = new Thread(connection);
				t.start();
			}
		} catch (IOException ioe) {
			ChatServer.logger.log(Level.WARNING, "IOException on socket listen: " + ioe + "");
		}
	}

	@Override
	public void onMessageReceived(Connect connect, String message) {
		// TODO Auto-generated method stub
		User user = userManager.getUser(connect);
		
		msgManager.onGetMessage(user, message);
	}

}
